package com.yanqu.road.server.manger.cross3;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.able.ActivityAbleInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.rank.eRankInfo;
import com.yanqu.road.entity.enums.rank.eRankRangeType;
import com.yanqu.road.entity.rank.xrank.XChannelRankPart;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.entity.rank.xrank.XUserRank;
import com.yanqu.road.logic.xlogic.rank.user.entiety.XUserRankChangeParam;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.able.ActivityAbleMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.pb.PlayerPb;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChannelRankActivityMgr extends TempMgr {

    private static Map<Integer, ActivityInfo> infoMap = new ConcurrentHashMap<>();

    public static Map<Integer, ActivityInfo> getInfoMap() {
        return infoMap;
    }

    public static void reloadActivityData() {
        getLogger().info("reload ChannelRankActivity start");
        // 获取活动信息（提前24小时加载）
        Map<Integer, ActivityInfo> tmpMap = new ConcurrentHashMap<>();
        for (ActivityInfo info : NormalActivityMgr.getShowTimeActivityInfoMap().values()) {
            if (info.getType() == eActivityType.ChannelRankActivity.getValue() && ActivityMgr.activityInLoadTime(info)) {
                tmpMap.put(info.getActivityId(), info);
            }
        }
        // 替换
        infoMap = tmpMap;
        getLogger().info("reload ChannelRankActivity finish! {} activity in show time.", infoMap.size());

        // 凭证、资格
        addUserActivityAbleListener();

        getLogger().info("AreaRankActivity able finish!");
    }

    /**
     * 添加活动资格监听
     */
    private static void addUserActivityAbleListener() {
        // 配置
        Map<Integer, ActivityAbleInfo> ableInfoMap = new ConcurrentHashMap<>();
        for (ActivityInfo info : infoMap.values()) {
            ActivityAbleInfo ableInfo = new ActivityAbleInfo();
            ableInfo.setActivityInfo(info);
            ableInfo.setAbleItemId(Integer.valueOf(info.getParam4()));
            ableInfoMap.put(info.getActivityId(), ableInfo);
        }

        // 添加监听
        ActivityAbleMgr.addActivityAbleListener(eActivityType.ChannelRankActivity.getValue(), ableInfoMap,
                (ableInfo, userId) -> {
                    // 排行榜变更
                    ChannelRankActivityMgr.refreshRankValue(ableInfo.getActivityInfo().getActivityId(), userId);
                }
        );
    }

    /**
     * 修改个人排行榜
     */
    public static void userRankChange(int activityId, int conditionType, long value, long userId, String param) {

        // 判断资格
        if (!ActivityAbleMgr.isAble(userId, activityId)) {
            return;
        }

        XUserRank userRank = new XUserRank();
        userRank.setActivityId(activityId);
        userRank.setConditionType(conditionType);
        userRank.setChannelId(ServerListMgr.getChannelId(GameServer.getInstance().getServerId()));
        userRank.setServerId(GameServer.getInstance().getServerId());
        userRank.setUserId(userId);
        userRank.setBaseInfo(PlayerBasePb.parseBaseUserInfo(PlayerPb.parsePlayerBaseTempMsg(UserMgr.getUserInfo(userId)).build()));
        userRank.setParam(param);
        userRank.setValue(BigInteger.valueOf(value));
        userRank.setLastUpdateTime(System.currentTimeMillis());

        GameXRankMgr.getUserRankMap().userRankChange(userRank, new XUserRankChangeParam(true));
    }

    /**
     * 修改区域榜个人值
     */
    public static void channelRankPartChange(int activityId, int conditionType, long value, long userId) {

        // 判断资格
        if (!ActivityAbleMgr.isAble(userId, activityId)) {
            return;
        }

        XChannelRankPart rankPart = new XChannelRankPart(
                activityId,
                conditionType,
                ServerListMgr.getChannelId(GameServer.getInstance().getServerId()),
                userId,
                UserMgr.getUserInfo(userId).getNickName(),
                BigInteger.valueOf(value < 0 ? 0 : value),
                System.currentTimeMillis()
        );

        GameXRankMgr.getChannelRankMap().partValueChange(rankPart, true, false);
    }

    /**
     * 刷新榜单值
     */
    public static void refreshRankValue(int activityId, long userId) {

        // 判断资格
        if (!ActivityAbleMgr.isAble(userId, activityId)) {
            return;
        }

        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
        if (activityInfo == null) {
            getLogger().error("user {}, activityId {}, refreshRankValue but no activityInfo!", userId, activityId);
            return;
        }

        // 拿condition类型（冲榜活动值都记在个人榜的condition）
        eRankInfo rankInfo = null;
        List<eRankInfo> rankInfoList = eRankInfo.getERankInfoList(activityInfo.getType(), activityInfo.getChildType());
        for (eRankInfo tmpInfo : rankInfoList) {
            if (tmpInfo.getRangeType() == eRankRangeType.User) {
                rankInfo = tmpInfo;
                break;
            }
        }

        // 拿涨幅
        long value = 0L;
        if (rankInfo != null) {
            // 在线玩家：读内存condition更新榜单
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if (onlinePlayer != null) {
                UserActivityConditionData userRankCondition = onlinePlayer.getModule(ActivityModule.class).getUserRankCondition(activityId, rankInfo.getConditionType());
                if (userRankCondition != null) {
                    value = userRankCondition.getValue().longValue();
                }
            } else {
                // 离线玩家：读数据库condition更新榜单
                List<Integer> activityIdList = new ArrayList<>();
                activityIdList.add(activityId);
                Map<Integer, List<UserActivityConditionData>> cacheDbCondition = UserActivityBussiness.getUserActivityConditionDataMap(userId, activityIdList);
                List<UserActivityConditionData> dataList = cacheDbCondition.get(rankInfo.getConditionType());
                if (dataList != null && dataList.size() > 0) {
                    value = dataList.get(0).getValue().longValue();
                }
            }
        }

        // 遍历榜单更新
        for (eRankInfo tmpInfo : rankInfoList) {
            if (tmpInfo.getRangeType() == eRankRangeType.User) {
                userRankChange(activityInfo.getActivityId(), tmpInfo.getConditionType(), value, userId, "");
            } else if (tmpInfo.getRangeType() == eRankRangeType.Channel) {
                channelRankPartChange(activityInfo.getActivityId(), tmpInfo.getConditionType(), value, userId);
            }
        }
    }


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }
}
